package com.briup.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.briup.cms.dao.ArticleDao;
import com.briup.cms.dao.CommentDao;
import com.briup.cms.dao.UserDao;
import com.briup.cms.domain.Comment;
import com.briup.cms.domain.Subcomment;
import com.briup.cms.dao.SubcommentDao;
import com.briup.cms.domain.User;
import com.briup.cms.domain.param.CommentQueryParam;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.ISubcommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.cms.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author briup
 * @since 2023-03-09
 */
@Service
public class SubcommentServiceImpl implements ISubcommentService {
    @Autowired
    UserDao userDao;
    @Autowired
    CommentDao commentDao;
    @Autowired
    SubcommentDao subcommentDao;

    @Override
    public void addSubComment(Subcomment subcomment) {
        if(subcomment == null)
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        if(subcomment.getUserId()==null || subcomment.getParentId()==null)
            throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE);

        User user = userDao.selectById(subcomment.getUserId());
        if(user == null)
            throw new ServiceException(ResultCode.DATA_NONE);

        Comment comment = commentDao.selectById(subcomment.getParentId());
        if(comment == null)
            throw new ServiceException(ResultCode.DATA_NONE);

        subcomment.setPublishTime(LocalDateTime.now());
        subcommentDao.insert(subcomment);
    }

    @Override
    public void deleteById(Long id) {
        subcommentDao.deleteById(id);
    }

    @Override
    public List<Subcomment> queryByParentId(Long parentId) {
        LambdaQueryWrapper<Subcomment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subcomment::getParentId,parentId);
        wrapper.orderByAsc(Subcomment::getPublishTime);
        List<Subcomment> subcomments = subcommentDao.selectList(wrapper);
        return subcomments;
    }

    @Override
    public IPage<Subcomment> query(CommentQueryParam param) {
        LambdaQueryWrapper<Subcomment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(param.getUserId()!=null,Subcomment::getUserId,param.getUserId());
        wrapper.like(param.getContent()!=null,Subcomment::getContent,param.getContent());
        wrapper.between(Subcomment::getPublishTime,param.getStartTime(),param.getEndTime());
        Page<Subcomment> page = new Page<>(param.getPageNum(), param.getPageSize());
        subcommentDao.selectPage(page,wrapper);
        return page;
    }


}
